rm(list = ls())
library(spatialreg)
library(cshapes)
library(tidyverse)
library(sf)
library(stargazer)
library(lubridate)
library(tscsdep)
library(texreg)
library(spdep)
load("data/data_imputed.RData")

data  <- data_imputed
data <- data %>% 
       dplyr::rename(country = country_name) 

## lag all IV for one year
data <- data %>% 
       dplyr::arrange(cowcode, year) %>% 
       dplyr::group_by(cowcode) %>% 
       dplyr::mutate_at(vars(c("logpop", "loggdppc", "tradependonCHN",
                               "v2x_polyarchy", "polity2", "capratio",
                               "dip_hist", "USpresident_visit","solschange",
                               "statehead.total", "statefrom.total",
                               "stateto.total")), ~dplyr::lag(.,n = 1L))  

data <- data %>% 
       dplyr::arrange(cowcode, year) %>% 
       dplyr::group_by(cowcode) %>% 
       dplyr::mutate(laglogidealdistance = dplyr::lag(logidealdistance, n = 1L),
                     lagagree = dplyr::lag(agree, n=1L))

data <- data %>% 
       dplyr::filter(!is.na(statefrom.total)) %>% 
       ungroup()

#Table A4. Robustness Check: The Impact of Chinese Leadership Visits on Foreign Policy Convergence (Pre-2008 vs Post-2008)

data <- data %>% 
       dplyr::mutate(post08 = ifelse(year >= 2008, 1, 0))

data5 <- data %>% dplyr::filter(post08 == 1)
data6 <- data %>% dplyr::filter(post08 == 0)

reg5 <-lm(formula = logidealdistance ~ laglogidealdistance + statefrom.total +
                 logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                 dip_hist + solschange +
                 factor(cowcode) + factor(year), 
          data = data5)
summary(reg5)$coefficients

wm5 <- make_ntspmat(lmobj = reg5, ci = "country", yi = "year", k = 5)
sar5 <- ntspreg(reg5, wm = wm5)
summary(sar5)

library(spdep)
weights5 <- mat2listw(wm5[[2]], row.names = NULL, style = "W")
nblist5 <- weights5$neighbours
listw5 <- nb2listw(nblist5)

slx5 <- lmSLX(logidealdistance ~ laglogidealdistance + statefrom.total +
                     logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                     dip_hist + solschange + factor(cowcode) + factor(year), data = data5,
              listw = listw5, Durbin = ~statefrom.total)
summary(slx5)

reg6 <-lm(formula = logidealdistance ~ laglogidealdistance + statefrom.total +
                 logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                 dip_hist + solschange +
                 factor(cowcode) + factor(year), 
          data = data6)
summary(reg6)$coefficients
wm6 <- make_ntspmat(lmobj = reg6, ci = "country", yi = "year", k = 5)
sar6 <- ntspreg(reg6, wm = wm6)
summary(sar6)

library(spdep)
weights6 <- mat2listw(wm6[[2]], row.names = NULL, style = "W")
nblist6 <- weights6$neighbours
listw6 <- nb2listw(nblist6)

slx6 <- lmSLX(logidealdistance ~ laglogidealdistance + statefrom.total +
                     logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                     dip_hist + solschange + factor(cowcode) + factor(year), data = data6,
              listw = listw6, Durbin = ~statefrom.total)
summary(slx6)
save(reg5, reg6, sar5, sar6, slx5, slx6,  file = "./Newcode2022/appendix2.RData")

# output to Table A4
texreg(list( reg6,  sar6,slx6, reg5, sar5,  slx5),
          file = "tables/app_2008.tex",
          custom.model.names = c("M1:OLS", "M2:SAR", "M3:SLX", "M4:OLS", "M5:SAR","M6:SLX"),
          stars = c(0.01, 0.05, 0.1),
          label = "tab:apped1",
          scalebox = 0.8,
          caption = "Robustness Check: The Impact of Chinese Leadership Visits on Foreign Policy Convergence (Pre-2008 vs Post-2008)",
          caption.above = TRUE,
          custom.header = list("Pre-2008 Period" = 1:3,
                               "Post-2008 Period" = 4:6),
          custom.coef.map = list("laglogidealdistance" = "Temporal Lagged DV",
                                 "lagagree" = "Temporal Lagged DV",
                                 "statefrom.total" = "Chinese State Visits",
                                 "$\\rho$" = "Spatial Lag Parameter: $\\rho$",
                                 "lag.statefrom.total" = "$\\boldsymbol{W_x}$: Chinese State Visits",
                                 "logpop" = "Ln(Population)",
                                 "loggdppc" = "Ln(GDP per Capita)",
                                 "tradependonCHN" = "Trade Dependence",
                                 "v2x_polyarchy" = "Electoral Democracy Index",
                                 "capratio" = "Capability Ratio",
                                 "dip_hist" = "Years of Diplomatic Relations",
                                 "solschange" = "Change in Source of Leader Support"),
          custom.gof.rows = list("Fixed Country Effects" = c("YES", "YES", "YES", "YES", "YES", "YES"),
                                 "Fixed Year Effects" = c("YES", "YES", "YES", "YES", "YES", "YES")),
          digits = 4)


## Table A5. Robustness Check: The Impact of Chinese Leadership Visits on Foreign Policy Convergence across Administrations

data <- data %>% 
       dplyr::mutate(deng = ifelse(year < 1990, 1, 0),
                     jiang = ifelse(year >= 1990 & year < 2002, 1, 0),
                     hujintao = ifelse(year >=2002 & year < 2013, 1, 0),
                     xijinping = ifelse(year >= 2013, 1, 0)
                                       )
data1 <- data %>% dplyr::filter(deng == 1)
data2 <- data %>% dplyr::filter(jiang == 1)
data3 <- data %>% dplyr::filter(hujintao == 1)
data4 <- data %>% dplyr::filter(xijinping == 1)


reg1 <-lm(formula = logidealdistance ~ laglogidealdistance + statefrom.total +
                 logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                 dip_hist + solschange +
                 factor(cowcode) + factor(year), 
          data = data1)

wm1 <- make_ntspmat(lmobj = reg1, ci = "country", yi = "year", k = 5)
sar1 <- ntspreg(reg1, wm = wm1)



weights1 <- mat2listw(wm1[[2]], row.names = NULL, style = "W")
nblist1 <- weights1$neighbours
listw1 <- nb2listw(nblist1)

slx1 <- lmSLX(logidealdistance ~ laglogidealdistance + statefrom.total +
                    logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                    dip_hist + solschange + factor(cowcode) + factor(year), data = data1,
             listw = listw1, Durbin = ~statefrom.total)


reg2 <-lm(formula = logidealdistance ~ laglogidealdistance + statefrom.total +
                 logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                 dip_hist + solschange +
                 factor(cowcode) + factor(year), 
          data = data2)


wm2 <- make_ntspmat(lmobj = reg2, ci = "country", yi = "year", k = 5)
sar2 <- ntspreg(reg2, wm = wm2)


library(spdep)
weights2 <- mat2listw(wm2[[2]], row.names = NULL, style = "W")
nblist2 <- weights2$neighbours
listw2 <- nb2listw(nblist2)

slx2 <- lmSLX(logidealdistance ~ laglogidealdistance + statefrom.total +
                     logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                     dip_hist + solschange + factor(cowcode) + factor(year), data = data2,
              listw = listw2, Durbin = ~statefrom.total)

reg3 <-lm(formula = logidealdistance ~ laglogidealdistance + statefrom.total +
                 logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                 dip_hist + solschange +
                 factor(cowcode) + factor(year), 
          data = data3)

wm3 <- make_ntspmat(lmobj = reg3, ci = "country", yi = "year", k = 5)
sar3 <- ntspreg(reg3, wm = wm3)


library(spdep)
weights3 <- mat2listw(wm3[[2]], row.names = NULL, style = "W")
nblist3 <- weights3$neighbours
listw3 <- nb2listw(nblist3)

slx3 <- lmSLX(logidealdistance ~ laglogidealdistance + statefrom.total +
                     logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                     dip_hist + solschange + factor(cowcode) + factor(year), data = data3,
              listw = listw3, Durbin = ~statefrom.total)

reg4 <-lm(formula = logidealdistance ~ laglogidealdistance + statefrom.total +
                 logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                 dip_hist + solschange +
                 factor(cowcode) + factor(year), 
          data = data4)
summary(reg4)
wm4 <- make_ntspmat(lmobj = reg4, ci = "country", yi = "year", k = 5)
sar4 <- ntspreg(reg4, wm = wm4)
summary(sar4)

library(spdep)
weights4 <- mat2listw(wm4[[2]], row.names = NULL, style = "W")
nblist4 <- weights4$neighbours
listw4 <- nb2listw(nblist4)

slx4 <- lmSLX(logidealdistance ~ laglogidealdistance + statefrom.total +
                     logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                     dip_hist + solschange + factor(cowcode) + factor(year), data = data4,
              listw = listw4, Durbin = ~statefrom.total)
summary(slx4)

save(reg1, reg2, reg3, reg4, sar1, sar2, sar3, sar4, slx1, slx2, slx3,slx4, file = "./Newcode2022/appendix1.RData")

# Output to table A5
texreg(list( sar1, sar2, sar3, sar4),
       file = "tables/app_president.tex",
       custom.model.names = c("M1:Deng Xiaoping", "M2:Jiang Zeming", "M3:Hu Jintao", "M4:Xi Jinping"),
       stars = c(0.01, 0.05, 0.1),
       label = "tab:apped2",
       scalebox = 0.8,
       caption = "Robustness Check: The Impact of Chinese Leadership Visits on Foreign Policy Convergence across Administrations",
       caption.above = TRUE,
       custom.coef.map = list("laglogidealdistance" = "Temporal Lagged DV",
                              "lagagree" = "Temporal Lagged DV",
                              "statefrom.total" = "Chinese State Visits",
                              "$\\rho$" = "Spatial Lag Parameter: $\\rho$",
                              "logpop" = "Ln(Population)",
                              "loggdppc" = "Ln(GDP per Capita)",
                              "tradependonCHN" = "Trade Dependence",
                              "v2x_polyarchy" = "Electoral Democracy Index",
                              "capratio" = "Capability Ratio",
                              "dip_hist" = "Years of Diplomatic Relations",
                              "solschange" = "Change in Source of Leader Support"),
       custom.gof.rows = list("Fixed Country Effects" = c("YES", "YES", "YES", "YES"),
                              "Fixed Year Effects" = c("YES", "YES", "YES", "YES")),
       digits = 4)


### Table A6. Robustness Check: The Impact of Chinese Leadership Visits on Foreign Policy Convergence

data <- data %>% 
       dplyr::mutate(statefrom_dum = ifelse(statefrom.total >0, 1, 0))

table(data$statefrom_dum)

reg1 <-lm(formula = logidealdistance ~ laglogidealdistance + statefrom_dum +
                 logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                 dip_hist + solschange +
                 factor(cowcode) + factor(year), 
          data = data)

wm1 <- make_ntspmat(lmobj = reg1, ci = "country", yi = "year", k = 5)
sar1 <- ntspreg(reg1, wm = wm1)


## NATO
ally <- read_csv("data/atop5_0ddyr.csv")

ally <- ally %>% dplyr::select(ddyad, year, stateA, stateB,defense, offense) %>% 
              dplyr::filter(stateA == 2)
data <- left_join(data, ally, by = c("cowcode" = "stateB", "year" = "year"))

data <- data %>% dplyr::mutate(defense = ifelse(is.na(defense), 0, defense))
table(data$defense)

reg2 <-lm(formula = logidealdistance ~ laglogidealdistance + statefrom.total +defense+
                 logpop + loggdppc + tradependonCHN + v2x_polyarchy + capratio + 
                 dip_hist + solschange +
                 factor(cowcode) + factor(year), 
          data = data)
wm2 <- make_ntspmat(lmobj = reg2, ci = "country", yi = "year", k = 5)
sar2 <- ntspreg(reg2, wm = wm2)


# Output to Table A6
texreg(list(reg1, sar1, reg2, sar2),
       file = "tables/app_alliance.tex",
       custom.model.names = c("M1:OLS", "M2:SAR", "M3:OLS", "M4:SAR"),
       stars = c(0.01, 0.05, 0.1),
       label = "tab:apped3",
       scalebox = 0.8,
       caption = "Robustness Check: The Impact of Chinese Leadership Visits on Foreign Policy Convergence across Administrations",
       caption.above = TRUE,
       custom.coef.map = list("laglogidealdistance" = "Temporal Lagged DV",
                              "lagagree" = "Temporal Lagged DV",
                              'statefrom_dum' = "Chinese State Visits (dummy)",
                              "statefrom.total" = "Chinese State Visits",
                              "$\\rho$" = "Spatial Lag Parameter: $\\rho$",
                              "logpop" = "Ln(Population)",
                              "loggdppc" = "Ln(GDP per Capita)",
                              "tradependonCHN" = "Trade Dependence",
                              "v2x_polyarchy" = "Electoral Democracy Index",
                              "capratio" = "Capability Ratio",
                              "dip_hist" = "Years of Diplomatic Relations",
                              "defense" = "Defense alliance with the US",
                              "solschange" = "Change in Source of Leader Support"),
       custom.gof.rows = list("Fixed Country Effects" = c("YES", "YES", "YES", "YES"),
                              "Fixed Year Effects" = c("YES", "YES", "YES", "YES")),
       digits = 4)

